//
//  AudioDetailViewController.m
//  CommunityNannyO2O
//
//  Created by 90 on 15/7/21.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "AudioDetailViewController.h"
#import "AppConfig.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "MJExtension.h"
#import "AccountTool.h"
#import "UIViewController+Create.h"
#import <AVFoundation/AVFoundation.h>
#import "AudioPlayer.h"
#import "UIImageView+WebCache.h"
#import "STKAudioPlayer.h"
#import "FileDownloader.h"

@interface AudioDetailViewController()<QXNetWorkToolDelegate,AudioPlayerDeletage,STKAudioPlayerDelegate,STKDataSourceDelegate>


@property (weak, nonatomic) IBOutlet UILabel *audioLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailLabel;
//@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UISlider *videoSlider;

@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UILabel *starTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *image;

@property (nonatomic,copy) NSString *songId;
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *detail;
@property (nonatomic,copy) NSString *totalTime;

@property (assign,nonatomic) BOOL isPlay;

@property (nonatomic ,strong) STKAudioPlayer *audioPlayer;

@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;

@property (nonatomic,strong )  AVAudioPlayer *aaudioPlayer;

@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,strong)  FileDownloader * fileDownloader;

@property (nonatomic,assign) BOOL isDownLoad;


@property (strong, nonatomic)  UIView *downLoadView;

@property (strong, nonatomic)  UIProgressView *downLoadProgress;

@property (strong, nonatomic)  UILabel *downLoadLabel;

@property (strong,nonatomic) UIView *darkView;



@end


@implementation AudioDetailViewController


- (void)viewDidLoad
{    
    [super viewDidLoad];
    
    self.audioLabel.text = self.name;
    
    self.detailLabel.text = self.detail;
    
    [self configNavigationItem];
    
    self.videoSlider.continuous = NO;   //拖动不触发
    
    self.videoSlider.value = 0.0;
   
    [self.videoSlider addTarget:self action:@selector(updateValue) forControlEvents:UIControlEventValueChanged];
    
    [self.videoSlider setThumbImage:[UIImage imageNamed:@"ico_audio_detai_slider"] forState: UIControlStateNormal];
    
    self.starTimeLabel.text = [self convertTime:0.0];
    
    
    NSURL * url = [NSURL URLWithString:self.cover_img];
    
   // [self PlayerAndPause:self.playBtn];
    
    [self.image sd_setImageWithURL:url];
    
    self.starTimeLabel.text = [self convertTime:0.0];
    
    [self configDownloadView];
    
    
    [self playMusic];
    
}

- (void)checkMp3IsDownLoad{
    
    if (_isDownLoad) {
        
    
    }else {
    
    
    }
}


- (FileDownloader *)fileDownloader{

    if (!_fileDownloader) {
        
        
        
    }
    
    return _fileDownloader;
}


- (void)configDownloadView{

    
    _darkView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWindowWidth, kWindowHeight)];
    
    _darkView.backgroundColor = [UIColor blackColor];
    
    _darkView.alpha = 0.4;

    [self.view addSubview:_darkView];

    
    _downLoadView = [[UIView alloc]initWithFrame:CGRectMake(40, kWindowHeight * 0.5 - 60 , kWindowWidth - 80, 100)];
    
    [self.downLoadView.layer setCornerRadius:8.0];
    
    [self.downLoadView.layer setMasksToBounds:YES];
    
    _downLoadView.backgroundColor = [UIColor whiteColor];
  
    _downLoadProgress = [[UIProgressView alloc]initWithFrame:CGRectMake(50, 50, 70, 10)];
    
    _downLoadLabel = [[UILabel alloc]initWithFrame:CGRectMake(_downLoadView.center.x - 80, 20, 70, 10)];
    
    _downLoadLabel.font = [UIFont boldSystemFontOfSize:14];
    
    _downLoadLabel.textAlignment = NSTextAlignmentCenter;
    
    _downLoadLabel.text = @"正在下载";
    
    
    _downLoadLabel.textColor = [UIColor blackColor];
    
    //_downLoadProgress.backgroundColor = [UIColor redColor];
    
    
    [self.view addSubview:_downLoadProgress];
    
   [_downLoadView addSubview:_downLoadLabel];
    
  //  [self.view addSubview:_downLoadView];
    
  
    
    
    
}


-(void)setProgressStartTime:(float)startTime EndTime:(float)endTime
{
    
    self.starTimeLabel.text = [self convertTime:startTime];
    
    self.endTimeLabel.text = [self convertTime:endTime];
    
    self.videoSlider.value = startTime / endTime;//滑动条的当前值
   
    
    [MBProgressHUD hideHUD];
}

- (NSString *)convertTime:(CGFloat)second{
 
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
    
    return showtimeNew;
}

- (void)setAudioName:(NSString *)name Detial:(NSString *)str Url:(NSString *)url
{
    self.name = name;
    self.detail = str;
    self.url = url;
}

- (IBAction)PlayerAndPause:(id)sender
{
    
    if (self.isPlay) {
        
        [self.audioPlayer pause];
        
        [self.playBtn setImage:[UIImage imageNamed:@"ico_audio_detai_player"] forState:UIControlStateNormal];
        
        self.isPlay = NO;
        
    }else {
    
        [self.audioPlayer resume];
    
       
        
          [self.playBtn setImage:[UIImage imageNamed:@"ico_audio_detai_pause"] forState:UIControlStateNormal];
        
        self.isPlay = YES;
    
    }
    
    
    
//    if ([self.audioPlayer isBegin])
//    {
//        if ([self.audioPlayer isPlaying])
//        {
//            [self.audioPlayer pause];
//            
//            [self.playBtn setBackgroundImage:[UIImage imageNamed:@"ico_audio_detai_pause"]
//                                    forState:UIControlStateNormal];
//        }
//        else if ([self.audioPlayer isPaused])
//        {
//            [self.audioPlayer start];
//            
//            [self.playBtn setBackgroundImage:[UIImage imageNamed:@"ico_audio_detai_player"]
//                                    forState:UIControlStateNormal];
//        }
//        else if ([self.audioPlayer isFinishing])
//        {
//            [self.audioPlayer stop];
//            
//            [self.playBtn setBackgroundImage:[UIImage imageNamed:@"ico_audio_detai_pause"]
//                                    forState:UIControlStateNormal];
//        }
//    }
//    else
//    {
//        //    http://music.baidutt.com/up/kwcawpcw/dumkk.mp3
//        self.audioPlayer.url = [NSURL URLWithString:@"http://music.baidutt.com/up/kwcawpcw/yuydsw.mp3"];
//        
//        [self.audioPlayer play];
//        
//        [self.playBtn setBackgroundImage:[UIImage imageNamed:@"ico_audio_detai_player"]
//                                forState:UIControlStateNormal];
//    }
}

- (IBAction)share:(id)sender
{
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
//    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:LoginInterface andParameter:@[@{@"password":_phone.text}] tag:2];
    
    
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{

    switch (tag)
    {
        case 1:
            
            if (Response == nil)
            {
                
                return;
            }
            
            
            for (NSDictionary *dic in Response)
            {

            }
            
            break;
          
        case 2:
            for (NSDictionary *dic in Response)
            {
                [self.navigationController popViewControllerAnimated:YES];

            }

    }
}

-(void)configNavigationItem
{
    self.navigationItem.title = self.name;
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar
     setBackgroundImage:[UIImage imageNamed:@"bg_login_statue_bar"]
     forBarMetrics:UIBarMetricsDefault];
    
    //status bar的字体为白色
    //导航栏的背景色是黑色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSFontAttributeName,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.audioPlayer stop];
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(void)useMethodToFindBlackLineAndHind
{
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self configNavigationItem];

    [self useMethodToFindBlackLineAndHind];
}

-(void)viewDidAppear:(BOOL)animated{

 
    
    
}


#pragma mark 进入页面 开始播放音乐

- (void) playMusic{

    self.audioPlayer = [[STKAudioPlayer alloc] init];
    
    self.isPlay = YES;
    
    [self.playBtn setImage:[UIImage imageNamed:@"ico_audio_detai_pause"]
                  forState:UIControlStateNormal];
    
    [self.audioPlayer playURL: [NSURL URLWithString:self.url]];
    
    self.audioPlayer.delegate = self;

}

#pragma mark 播放器的代理


-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId{
    
    
    self.endTimeLabel.text = [self convertTime:audioPlayer.duration];
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    
    self.endTimeLabel.text = [self convertTime:audioPlayer.duration];
    
    
    self.videoSlider.minimumValue = 0.0;
    
    self.videoSlider.maximumValue = audioPlayer.duration;
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    
}

/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId{
    
    
    [self.audioPlayer  playURL:[NSURL URLWithString:self.url]];
    
    
}


- (void)timeFireMethod{
    
    
    _starTimeLabel.text = [self convertTime:self.
                           audioPlayer.progress];
    
    self.videoSlider.value = self.audioPlayer.progress;
    
}


- (void)updateValue{
    
    
    
    [self.audioPlayer seekToTime:self.videoSlider.value];
    
    self.starTimeLabel.text = [self convertTime:self.
                               audioPlayer.progress];
    
}
@end



















